package com.tucc.hello.leetcode.no1_400.no1_200.no41_60.no54;

import java.util.ArrayList;
import java.util.List;

/**
 * @author tucc
 * @description todo
 * @package com.tucc.hello.leetcode
 * @date 2021/5/20
 **/
public class Solution {

    public static void main(String[] args) {
        Solution solution = new Solution();
        int[][] matrix = {{1, 2, 3, 4}, {5, 6, 7, 8}, {9, 10, 11, 12}};

        matrix = new int[][]{{1, 2}, {3, 4}, {5, 6}, {7, 8}};
        matrix = new int[][]{{1}, {2}, {3}, {4}};
        List<Integer> result = solution.spiralOrder(matrix);
        System.out.println(result);

    }

    public List<Integer> spiralOrder(int[][] matrix) {
        List<Integer> result = new ArrayList<>();
        if (matrix.length > 0) {
            int m = matrix.length;
            int n = matrix[0].length;
            int mc = Math.min((m - 1) / 2, (n - 1) / 2);
            spiralOrder(matrix, 0, mc, m, n, result);
        }
        return result;
    }


    public void spiralOrder(int[][] matrix, int c, int mc, int m, int n, List<Integer> result) {
        if (n > 0) {
            for (int i = c; i < n - c; i++) {
                result.add(matrix[c][i]);
            }
            for (int i = c + 1; i < m - c; i++) {
                result.add(matrix[i][n - 1 - c]);
            }
            if (m - 1 - c != c) {
                for (int i = n - c - 2; i >= c; i--) {
                    result.add(matrix[m - 1 - c][i]);
                }
            }
            if(n - 1 - c != c) {
                for (int i = m - c - 2; i > c; i--) {
                    result.add(matrix[i][c]);
                }
            }
            if (c + 1 <= mc) {
                spiralOrder(matrix, c + 1, mc, m, n, result);
            }
        }
    }

}
